package com.ruoyi.common.dto;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.framework.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.validation.BindException;


import javax.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;


/**
 * @author ywh
 */
public class AppController extends BaseController {

    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;

    private static final Logger log = LoggerFactory.getLogger(AppController.class);


    /**
     * 获取得到微信端传递过来的参数方法一
     * @param request
     * @return
     * @throws Exception
     */
    public static String getJson(HttpServletRequest request) throws Exception{
        StringBuilder sb=new StringBuilder();//使用StringBuileder效率快，但是不线程安全
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        String s;
        while ((s=br.readLine())!=null){
            //当读取到request里面有数据，就回继续循环下去
            sb.append(s);//将参数进行拼接
        }
        System.out.println("=======getJson==========\n" + sb.toString() + "\n=======getJson==========");
        return sb.toString();
    }

    /**
     * 获取得到微信端传递过来的参数方法二
     * @return
     * @throws Exception
     */
    public JSONObject getJsonRequest() {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("=======getJson==========\n" + sb.toString() + "\n=======getJson==========");
        return result;
    }

    /**
     * 操作失败返回的map定义
     */
    public static Map<String,Object> writerResultFailure(){
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("code", ResultStatus.RESULT_STATUS_FAILURE);//失败的状态嘛
        map.put("msg",CodeEnum.getName(ResultStatus.RESULT_STATUS_FAILURE));//获取到操作失败的返回信息
        return map;
    }

    /**
     * 自定义错误返回信息
     */
    public static Map<String,Object> writeResultFailure(Object object){
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("code", ResultStatus.RESULT_STATUS_FAILURE);
        map.put("msg",object);
        return map;
    }

    /**
     * 操作成功返回
     */
    public static Map<String, Object> writeResultRep() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", ResultStatus.RESULT_STATUS_SUCCESS);
        map.put("msg", CodeEnum.getName(ResultStatus.RESULT_STATUS_SUCCESS));
        return map;
    }
    /**
     * 操作成功携带数据返回返回
     */
    public static Map<String, Object> writeResultRep(Object object) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", ResultStatus.RESULT_STATUS_SUCCESS);
        map.put("msg", CodeEnum.getName(ResultStatus.RESULT_STATUS_SUCCESS));
        map.put("data", object);
        return map;
    }

    /***自定义返回成功**/
    public static Map<String, Object> writeResultRep(Object object,String msg){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", ResultStatus.RESULT_STATUS_SUCCESS);
        map.put("msg", msg);
        map.put("data", object);
        return map;
    }

    /**
     * 其它返回码  throws Exception
     */
    public static Map<String, Object> writeResultRep(int code, String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    /**
     * 携带参数的其他返回码
     */
    public static Map<String, Object> writeResultRep(int code,Object object, String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", code);
        map.put("data", object);
        map.put("msg", msg);
        return map;
    }

    /**
     * 获取请求方IP
     *
     * @return 客户端Ip
     */
    public String getClientIp() {
        String xff = request.getHeader("X-Real-IP");
        if(xff!=null) {
            return xff;
        }
        xff = request.getHeader("x-forwarded-for");
        if (xff == null) {
            return "8.8.8.8";
        }
        return xff;
    }

//******************************************************************
    /**
     *第二种返回格式积累
     */
    /**
     * @param requestCode
     * @param msg
     * @param data
     * @return Map<String,Object>
     * @throws
     * @Description:构建统一格式返回对象
     * @date 2016年9月2日
     * @author zhuliyun
     */
    public Map<String, Object> toResponsObject(int requestCode, String msg, Object data) {
        Map<String, Object> obj = new HashMap<String, Object>();
        obj.put("code", requestCode);
        obj.put("msg", msg);
        if (data != null)
            obj.put("data", data);
        return obj;
    }

    public Map<String, Object> toResponsSuccess(Object data) {
        Map<String, Object> rp = toResponsObject(0, "执行成功", data);
        return rp;
    }

    public Map<String, Object> toResponsMsgSuccess(String msg) {
        return toResponsObject(0, msg, "");
    }

    public Map<String, Object> toResponsSuccessForSelect(Object data) {
        Map<String, Object> result = new HashMap<>(2);
        result.put("list", data);
        return toResponsObject(0, "执行成功", result);
    }

    public Map<String, Object> toResponsFail(String msg) {
        return toResponsObject(1, msg, null);
    }
/*=================================================统一异常处理=================================================================*/
    /**
     * 网站权限校验异常
     */
    @ExceptionHandler(AuthTokenException.class)
    @ResponseBody
    public Object handleAuthTokenException(AuthTokenException e){
        log.error(e.getMessage(), e);
        HashMap result=new HashMap();
        result.put("code",e.getCode());
        result.put("msg",e.getMsg());
        return result;
    }

    /**
     * 请求参数类型错误处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Object handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        HashMap result=new HashMap();
        result.put("code",500);
        result.put("msg","参数类型错误");
        return result;
    }
    /**
     * 缺失请求参数处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public Object handleMissingServletRequestParameterException(MissingServletRequestParameterException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        HashMap result=new HashMap();
        result.put("code",500);
        result.put("msg","缺少参数");
        return result;
    }

    /**
     * 参数类型错误异常类型处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    @ResponseBody
    public Object handleHttpMessageNotReadableException(HttpMessageConversionException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        HashMap result=new HashMap();
        result.put("code",500);
        result.put("msg","参数异常");
        return result;
    }
    /**
     * 空指针异常处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public Object handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        HashMap result=new HashMap();
        result.put("code",500);
        result.put("msg","空指针异常");
        return result;
    }

    /**
     * MethodArgumentNotValidException 异常处理
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        HashMap result=new HashMap();
        result.put("code",500);
        result.put("msg","校验异常");
        return result;
    }

    /**
     * 绑定异常处理
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Object handleBindException(BindException e,HttpServletRequest request){
        log.error(e.getMessage(), e);
        HashMap result=new HashMap();
        result.put("code",500);
        result.put("msg","绑定异常");
        return result;
    }

    /**
     * 处理运行时异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({RuntimeException.class})
    @ResponseBody
    public Object handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        HashMap result=new HashMap();
        result.put("code",500);
        result.put("msg","运行时异常");
        return result;
    }

    /**
     * 默认异常处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        HashMap result=new HashMap();
        result.put("code",500);
        result.put("msg","默认异常");
        return result;
    }

}













